package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    // 查询收货地址列表
    @Override
    public List<Address> findList() {
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());
        // 2.查询并返回
        return addressMapper.selectList(qw);
    }

    @Override
    public void add(Address address) {
        //设置条件
        address.setUserId(UserHolder.get().getId());
        addressMapper.insert(address);
    }

    @Override
    public Address findByid(Long id) {
        return addressMapper.selectById(id);
    }

    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void setDefault(Long id) {
        //根据userid修改所有地址的默认项
        Address address = new Address(); // set is_default =0
        address.setIsDefault(0);
        // 1-2 构建修改条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>(); // where user_id = ?
        qw.eq(Address::getUserId, UserHolder.get().getId());
        // 1-3 更新数据库
        addressMapper.update(address, qw);
        //2.将当前前端传递地址id设置为默认收货地址 update address_book set is_default =1 where id = ?
        Address address1 = new Address();
        address1.setIsDefault(1);
        address1.setId(id);
        addressMapper.updateById(address1);
    }

    @Override
    public Address findDefault() {
        //构造
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());
        qw.eq(Address::getIsDefault, 1);
        return addressMapper.selectOne(qw);
    }

    @Override
    public void delete(Long ids) {
        addressMapper.deleteById(ids);
    }
}
